<?php
/**
 * This file is part of webman.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author    walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link      http://www.workerman.net/
 * @license   http://www.opensource.org/licenses/mit-license.php MIT License
 */

namespace plugin\admin\app\exception;

use app\common\lib\Common;
use app\exception\IndexException;
use support\Cache;
use support\exception\BusinessException;
use Throwable;
use Webman\Http\Request;
use Webman\Http\Response;

/**
 * Class Handler
 * @package support\exception
 */
class HandlerException extends \support\exception\Handler
{
    public $dontReport = [
        BusinessException::class,
        AdminException::class,
        IndexException::class,
    ];

    public function report(Throwable $exception)
    {
        //parent::report($exception);
        $request = \request();
        if ($this->shouldntReport($exception)) {
            //正常的异常记录的请求结果
            $code = $exception->getCode();
            $message = $exception->getMessage();
            //todo 2 记录每次请求的参数和返回数据
            $responseData = ['code' => $code ?: 500, 'msg' => $message,'result' => null];;
            $headers = array_merge($request->header(),['ip'=>$request->getRealIp()]);

            $headerParam = json_encode($headers, 256);
            $requestParam = json_encode($request->allParam, 256);
            $responseParam = json_encode($responseData,256);
            $paramContent = '['.$request->url().'] '.$request->method()."\n";
            $paramContent .= "header: ".$headerParam."\n";
            $paramContent  .= "requestParam: ".$requestParam."\n";
            $paramContent  .= "responseData: ".$responseParam."\n";
            $paramContent  .= "execTime: ".round(microtime(true)-$request->startExceTime,3)."\n"."\n";
            //var_dump($paramContent);
            Common::createAndSaveLog($paramContent,'request');

            return;
        }

        $key = md5($exception->getMessage());
        if(Cache::get('execption_'.$key)){
            return '';
        }

        Cache::set('execption_'.$key,1,120);
        $headers = array_merge($request->header(),['ip'=>$request->getRealIp()]);
        $headerParam = json_encode($headers, 256);
        $requestParam = json_encode($request->all(), 256);

        //保存异常日记
        $paramContent = '['.$request->url().'] '.$request->method()."\n";
        $paramContent .= "header: ".$headerParam."\n";
        $paramContent  .= "requestParam: ".$requestParam."\n";
        Common::createAndSaveLog($paramContent . PHP_EOL . $exception,'exception');

        //发送异常通知
        $path = rtrim((config('app.app_url') ? config('app.app_url') : $request->host()),'/').'/test/viewlog/getview?dirpath='.runtime_path('logs/exception/log-'.date('Y-m-d').'.html');
        Common::saveExceptionLog($path,$exception->getMessage());
    }

    public function render(Request $request, Throwable $exception): Response
    {
        $code = $exception->getCode();
        $debug = $this->_debug ?? $this->debug;
        if ($request->expectsJson()) {
            $message = $debug ? $exception->getMessage() : 'Server internal error';
            if ($this->shouldntReport($exception)) {
                $message = $exception->getMessage();
            }
            $json = ['code' => $code ?: 500, 'msg' => $message, 'type' => 'failed'];
            $debug && $json['traces'] = (string)$exception;
            return new Response(200, ['Content-Type' => 'application/json'],
                \json_encode($json, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
        }
        $error = $debug ? \nl2br((string)$exception) : 'Server internal error';
        return new Response(500, [], $error);
    }
}
